package com.wkck.aspect;

import com.wkck.annotaion.AutoFill;
import com.wkck.constant.AutoFillConstant;
import com.wkck.context.BaseContext;
import com.wkck.enumeration.AutoFillParams;
import com.wkck.exception.NoCacheClearableException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * @Author: CK
 * @Date: 2023/12/28/17:07
 * @Description:
 */

@Aspect
@Component
@Slf4j
public class GlobalProjectAspect {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /***
    * @Author: CK
    * @Date: 2023/12/28
    * @Param: []
    * @return:
    * @Description: 清除Redis所有缓存切入点
    */
    @Pointcut("execution(* com.wkck.service.impl.*.*(..)) && @annotation(com.wkck.annotaion.ClearAllCache) && execution(* com.wkck.controller.admin.*.*(..))")
    public void clearAllCachePointCut() {}

    @Pointcut("execution(* com.wkck.mapper.*.*(..)) && @annotation(com.wkck.annotaion.AutoFill)")
    public void autoFillPointCut() {}

    /***
    * @Author: CK
    * @Date: 2024/2/10
    * @Param: [joinPoint]
    * @Description: 需要自动填充
    */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行字段的填充");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //得到签名方法
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        // 得到操作类型
        AutoFillParams fillParams = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) { return; }

        // 约定 参数第一位
        Object entity = args[0];

        // 得到操作的管理员id和当前时间
        LocalDateTime now = LocalDateTime.now();
        Long adminId = BaseContext.getCurrentId();

        switch (fillParams) {
            case INSERT:
                try {
                    Method create_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                    Method update_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                    Method create_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Integer.class);
                    Method update_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Integer.class);

                    create_user.invoke(entity, adminId.intValue());
                    update_user.invoke(entity, adminId.intValue());
                    create_time.invoke(entity, now);
                    update_time.invoke(entity, now);
                } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                break;
            case UPDATE:
                try {
                    Method update_time = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                    Method update_user = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Integer.class);

                    update_user.invoke(entity, adminId.intValue());
                    update_time.invoke(entity, now);
                } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                break;
        }
        log.info("字段填充结束");
    }

    /**
    * @Author: CK
    * @Date: 2024/2/10
    * @Param: [joinPoint]
    * @Description: 清空缓存
    */
    @After("clearAllCachePointCut()")
    public void clearAllCache(JoinPoint joinPoint) {
        log.info("清除所有缓存");

        Set<Object> keys = redisTemplate.keys("*");

        if (keys == null) {
            throw new NoCacheClearableException("没有缓存可清除");
        }

        redisTemplate.delete(keys);
        log.info("已成功清除所有缓存");
    }
}
